
//
//  ZFLineChart.m
//  ZFChartView
//
//  Created by apple on 16/2/15.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "ZFLineChart.h"
#import "ZFGenericChart.h"
#import "ZFLine.h"
#import "ZFCirque.h"
#import "ZFConst.h"
#import "ZFLabel.h"
#import "NSString+Zirkfied.h"

@interface ZFLineChart()<UIScrollViewDelegate>

/** 通用坐标轴图表 */
@property (nonatomic, strong) ZFGenericChart * genericChart;
/** 存储圆环的数组 */
@property (nonatomic, strong) NSMutableArray * cirqueArray;
/** 标题Label */
@property (nonatomic, strong) UILabel * titleLabel;

@end

@implementation ZFLineChart

- (NSMutableArray *)cirqueArray{
    if (!_cirqueArray) {
        _cirqueArray = [NSMutableArray array];
    }
    return _cirqueArray;
}

/**
 *  初始化变量
 */
- (void)commonInit{
    _isShowValueOnChart = YES;
    _valueOnChartFontSize = 10.f;
    _valueOnChartPosition = kLineChartValuePositionDefalut;
    _isShadow = YES;
    self.showsHorizontalScrollIndicator = NO;
    self.delegate = self;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
        [self drawGenericChart];
        self.bounces = NO;
        self.directionalLockEnabled = YES;
        //标题Label
        self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 30)];
        self.titleLabel.font = [UIFont boldSystemFontOfSize:12.f];
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.textColor = [UIColor darkGrayColor];
        [self addSubview:self.titleLabel];
    }
    
    return self;
}

#pragma mark - 坐标轴

/**
 *  画坐标轴
 */
- (void)drawGenericChart{
    self.genericChart = [[ZFGenericChart alloc] initWithFrame:self.bounds];
    [self addSubview:self.genericChart];
}

#pragma mark - 画圆环和线

/**
 *  画圆环和线
 */
- (void)drawLineAndCirque{
    [self removeAllLineAndCirque];
    [self removeLabelOnChart];
    [self.cirqueArray removeAllObjects];
    
    //线
    for (NSInteger i = 0; i <  self.xLineValueArray.count - 1; i++) {
        
        BOOL isOverrun = NO;//记录是否超出上限
        CGFloat percent = [self.xLineValueArray[i] floatValue] / _yLineMaxValue;
        CGFloat nextPercent = [self.xLineValueArray[i + 1] floatValue] / _yLineMaxValue;
        
        if (percent > 1) {
            percent = 1.f;
            isOverrun = YES;
        }
        
        CGFloat height = self.genericChart.yLineMaxValueHeight * percent;
        CGFloat nextHeight = self.genericChart.yLineMaxValueHeight * nextPercent;
        
        CGFloat y = self.genericChart.axisStartYPos - height;
        CGFloat x = self.genericChart.axisStartXPos + (XLineItemWidth + XLineItemGapLength) * i + XLineItemWidth / 2;
        
        CGFloat nextY = self.genericChart.axisStartYPos - nextHeight;
        CGFloat nextX = self.genericChart.axisStartXPos + (XLineItemWidth + XLineItemGapLength) * (i + 1) + XLineItemWidth / 2;
        
        CGFloat end_XPos = fabs(x - nextX);
        CGFloat end_YPos = nextY - y;
        ZFLine * line = [[ZFLine alloc] initWithStartPoint:CGPointMake(x, y) endPoint:CGPointMake(end_XPos, end_YPos)];
        line.isShadow = _isShadow;
        [line strokePath];
        [self.genericChart addSubview:line];
    }

    
    //圆环
    for (NSInteger i = 0; i < self.xLineValueArray.count; i++) {
        BOOL isOverrun = NO;//记录是否超出上限
        if (_yLineMaxValue == 0) {
            _yLineMaxValue = 0.01;
        }
        CGFloat percent = [self.xLineValueArray[i] floatValue] / _yLineMaxValue;
        if (percent > 1) {
            percent = 1.f;
            isOverrun = YES;
        }
        
        CGFloat height = self.genericChart.yLineMaxValueHeight * percent;
        CGFloat y = self.genericChart.axisStartYPos - height;
        CGFloat x = self.genericChart.axisStartXPos + (XLineItemWidth + XLineItemGapLength) * i + XLineItemWidth / 2;
      
        
        ZFCirque * cirque = [[ZFCirque alloc] initWithFrame:CGRectMake(x, y, 0, 0)];
        cirque.cirqueColor = [UtilCheck hexStringToColor:@"fb8411" alpha:1];
        
        //当前数值超过y轴显示上限时，圆环改为红色
        if (isOverrun == YES) {
            cirque.cirqueColor = [UIColor redColor];
        }
        cirque.isShadow = _isShadow;
        [cirque strokePath];
        [self.genericChart addSubview:cirque];
        [self.cirqueArray addObject:cirque];
        cirque.tag = 2000 + i;
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cirquePress:)];
        [cirque addGestureRecognizer:singleTap];
        
    }
    
   
    //圆环上的label
    _isShowValueOnChart ? [self addLabelOnChart] : nil;
   
    // 为折线背景添加渐变色
    //绘制渐变色层
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame =CGRectMake(0, 0, 400, 160) ;// self.view.frame;
    gradientLayer.colors = @[(__bridge id)[UIColor colorWithRed:244.f/255 green:133.f/255 blue:30.f/255 alpha:0.3].CGColor, (__bridge id)[UIColor colorWithRed:244.f/255 green:133.f/255 blue:30.f/255 alpha:0].CGColor];
    gradientLayer.locations=@[@0.0,@1.0];
    gradientLayer.startPoint = CGPointMake(0.0,0.0);
    gradientLayer.endPoint = CGPointMake(0.0,1);
    [self.layer addSublayer:gradientLayer];//加上渐变层
    
    UIBezierPath *gradPath = [[UIBezierPath alloc] init];
    for (NSInteger i = 0; i < self.xLineValueArray.count; i++) {
        BOOL isOverrun = NO;//记录是否超出上限
        if (_yLineMaxValue == 0) {
            _yLineMaxValue = 0.01;
        }
        CGFloat percent = [self.xLineValueArray[i] floatValue] / _yLineMaxValue;
        if (percent > 1) {
            percent = 1.f;
            isOverrun = YES;
        }
        CGFloat height = self.genericChart.yLineMaxValueHeight * percent;
        CGFloat y = self.genericChart.axisStartYPos - height;
        CGFloat x = self.genericChart.axisStartXPos + (XLineItemWidth + XLineItemGapLength) * i + XLineItemWidth / 2;
        
        if (0 == i) {
            [gradPath moveToPoint:CGPointMake(x, self.genericChart.axisStartYPos)];
            [gradPath addLineToPoint:CGPointMake(x, y)];
        }
        else if (self.xLineValueArray.count - 1 == i){
            [gradPath addLineToPoint:CGPointMake(x, y)];
            [gradPath addLineToPoint:CGPointMake(x, self.genericChart.axisStartYPos)];
        }
        else {
            [gradPath addLineToPoint:CGPointMake(x, y)];
        }
    }
    CAShapeLayer *arc = [CAShapeLayer layer];
    arc.path = gradPath.CGPath;
    arc.fillColor = [UIColor yellowColor].CGColor;
    arc.strokeColor = [UIColor yellowColor].CGColor;
    arc.lineWidth = 1;
    gradientLayer.mask = arc;
}


//WSP添加上下文和蓝色渐变
//- (void)drawRect:(CGRect)rect
//{
//    //1.获得图形上下文
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    CGPoint sPoints[self.cirqueArray.count + 2];//坐标点
//    for (NSInteger i = 0 ; i < self.cirqueArray.count; i ++ ) {
//        ZFCirque * cirque = self.cirqueArray[i];
//        sPoints[i] = CGPointMake(cirque.center.x, cirque.center.y);
//    }
//    ZFCirque * cirqueFirst = self.cirqueArray[0];
//    ZFCirque * cirqueLast = self.cirqueArray[self.cirqueArray.count - 1];
//
//    //取得最高点
//    NSMutableArray *tempArray = [NSMutableArray arrayWithArray:self.xLineValueArray];
//    NSInteger topY = [tempArray[0] integerValue];
//    int topYLocal = 0;
//    for (int i = 0 ; i < tempArray.count ; i ++) {
//        if (topY > [tempArray[i] integerValue]) {
//            topY = [tempArray[i] integerValue];
//            topYLocal = i;
//        }
//    }
//    
////    ZFCirque * cirqueTop = self.cirqueArray[topYLocal];
////    UIView *bGView = [[UIView alloc]initWithFrame:CGRectMake(cirqueFirst.center.x, cirqueTop.center.y + 5, cirqueLast.center.x - cirqueFirst.center.x, _genericChart.axisStartYPos - cirqueTop.center.y -5)];
//    
//    sPoints[self.cirqueArray.count + 1] = CGPointMake(cirqueFirst.center.x, _genericChart.axisStartYPos);
//    sPoints[self.cirqueArray.count] = CGPointMake(cirqueLast.center.x, _genericChart.axisStartYPos);
//    
////    CAGradientLayer *gradient1 = [CAGradientLayer layer];
////    gradient1.frame = bGView.bounds;
////    //设置渐变颜色方向
////    gradient1.startPoint = CGPointMake(0, 0);
////    gradient1.endPoint = CGPointMake(0, 1);
////    
////    //设定颜色组
////    gradient1.colors = @[(__bridge id)[UIColor colorWithRed:222.f/255 green:241.f/255 blue:251.f/255 alpha:0.9].CGColor,
////                                  (__bridge id)[UIColor whiteColor].CGColor];
////    //设定颜色分割点
//////    gradient1.locations = @[@(0.5f) ,@(1.0f)];
////    [bGView.layer insertSublayer:gradient1 atIndex:0];
//    
//    CGContextAddLines(context, sPoints, self.cirqueArray.count + 2);
//    UIColor*aColor = [UIColor colorWithRed:244.f/255 green:133.f/255 blue:30.f/255 alpha:0.15];
//    CGContextSetFillColorWithColor(context, aColor.CGColor);//填充颜色
//    aColor = [UIColor clearColor];
//    CGContextSetStrokeColorWithColor(context, aColor.CGColor);
//    CGContextClosePath(context);
//    CGContextDrawPath(context, kCGPathFillStroke);
////    self.layer.mask = gradient1;
////    bGView.alpha = 0.9;
////    [self addSubview:bGView];
//
//}

#pragma mark 圆环的点击事件
- (void)cirquePress:(UITapGestureRecognizer *)sender{
    
    [self.selectDelegate lineChartSelectedItemWithIndex:((int)sender.view.tag - 2000)];

    if (_isShowValueOnChart) {
        
        int btnTag = (int)sender.view.tag + 1000;
        int imgTag = (int)sender.view.tag + 2000;
        
        for (int i = 3000; i < 3000 + self.xLineValueArray.count; i ++) {
            if (btnTag == i) {
                UIButton *button = (UIButton *)[self viewWithTag:btnTag];
                button.hidden = !button.hidden;
            }
            else {
                UIButton *button = (UIButton *)[self viewWithTag:i];
                button.hidden = YES;
            }
        }
        
        for (int i = 4000; i < 4000 + self.xLineValueArray.count; i ++) {
            if (imgTag == i) {
                UIImageView *imageView = (UIImageView *)[self viewWithTag:imgTag];
                imageView.hidden = !imageView.hidden;
            }
            else {
                UIImageView *imageView = (UIImageView *)[self viewWithTag:i];
                imageView.hidden = YES;
            }
        }
    }
}


/**
 *  显示圆环上的label
 */
- (void)addLabelOnChart{
    //删除之前的 label
    
    //圆环上的label
    for (NSInteger i = 0; i < self.cirqueArray.count; i++) {
        ZFCirque * cirque = self.cirqueArray[i];
        //label的中心点
        CGPoint label_center = CGPointMake(0, 0);
        
        //_valueOnChartPosition为上下分布
        if (_valueOnChartPosition == kLineChartValuePositionDefalut) {
            //根据end_YPos判断label显示在圆环上面或下面
            CGFloat end_YPos;
            
            if (i < self.cirqueArray.count - 1) {//当前圆环不是最后一个时
                ZFCirque * nextCirque = self.cirqueArray[i+1];
                end_YPos = nextCirque.center.y - cirque.center.y;
                
            }else{//当前圆环为最后一个时
                ZFCirque * preCirque = self.cirqueArray[i-1];
                end_YPos = preCirque.center.y - cirque.center.y;
                
            }
            
            label_center = end_YPos <= 0 ? CGPointMake(cirque.center.x, cirque.center.y - 15) : CGPointMake(cirque.center.x, cirque.center.y - 15);
            
        //_valueOnChartPosition为圆环上方
        }else if (_valueOnChartPosition == kLineChartValuePositionOnTop){
            label_center = CGPointMake(cirque.center.x, cirque.center.y - 15);
            
        //_valueOnChartPosition为圆环下方
        }else if (_valueOnChartPosition == kLineChartValuePositionOnBelow){
            label_center = CGPointMake(cirque.center.x, cirque.center.y - 15);
            
        }
        
        UIButton *labelBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        labelBtn.frame = CGRectMake(0, 0, 24, 16);
        labelBtn.tag = 3000 + i;
        [labelBtn setTitle:self.xLineValueArray[i] forState:(UIControlStateNormal)];
        [labelBtn setBackgroundImage:BDFILEIMAGENAEM(@"mainVC/pointmsgbg") forState:(UIControlStateNormal)];
        labelBtn.titleLabel.font = [UIFont systemFontOfSize:10];
        labelBtn.center = CGPointMake(label_center.x, label_center.y - 3);
        [labelBtn setContentEdgeInsets:(UIEdgeInsetsMake(0, 0, 3.5, 0))];
      
        [self addSubview:labelBtn];
        
        
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, cirque.width + 2, cirque.height + 2)];
        imageView.center = cirque.center;
        imageView.tag = 4000 + i;
        
        imageView.image = BDFILEIMAGENAEM(@"mainVC/pointh");
        [self addSubview:imageView];
        
        if (i < self.xLineValueArray.count - 1) {
            labelBtn.hidden = YES;
            imageView.hidden = YES;
        }
    }
}

/**
 *  清除之前所有圆环和线
 */
- (void)removeAllLineAndCirque{
    for (UIView * view in self.genericChart.subviews) {
        if ([view isKindOfClass:[ZFLine class]] || [view isKindOfClass:[ZFCirque class]]) {
            [view removeFromSuperview];
        }
    }
}


/**
 *  清除圆环上的Label
 */
- (void)removeLabelOnChart{
    for (UIView * view in self.subviews) {
        if ([view isKindOfClass:[ZFLabel class]]) {
            [(ZFLabel *)view removeFromSuperview];
        }
    }
}

#pragma mark - public method

/**
 *  重绘
 */
- (void)strokePath{
    [self.genericChart strokePath];
    [self drawLineAndCirque];
    self.contentSize = CGSizeMake(CGRectGetWidth(self.genericChart.frame), self.frame.size.height);
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //self滚动时，标题保持相对不动
    self.titleLabel.frame = CGRectMake(self.contentOffset.x, self.titleLabel.frame.origin.y, self.titleLabel.frame.size.width, self.titleLabel.frame.size.height);
}

#pragma mark - 重写setter,getter方法

- (void)setXLineTitleArray:(NSMutableArray *)xLineTitleArray{
    _xLineTitleArray = xLineTitleArray;
    self.genericChart.xLineTitleArray = _xLineTitleArray;
}

- (void)setXLineValueArray:(NSMutableArray *)xLineValueArray{
    _xLineValueArray = xLineValueArray;
    self.genericChart.xLineValueArray = _xLineValueArray;
}

- (void)setYLineMaxValue:(float)yLineMaxValue{
    _yLineMaxValue = yLineMaxValue;
    self.genericChart.yLineMaxValue = _yLineMaxValue;
}

- (void)setYLineSectionCount:(NSInteger)yLineSectionCount{
    _yLineSectionCount = yLineSectionCount;
    self.genericChart.yLineSectionCount = _yLineSectionCount;
}

- (void)setTitle:(NSString *)title{
    _title = title;
    self.titleLabel.text = _title;
}

- (void)setXLineTitleFontSize:(CGFloat)xLineTitleFontSize{
    _xLineTitleFontSize = xLineTitleFontSize;
    self.genericChart.xLineTitleFontSize = _xLineTitleFontSize;
}

- (void)setXLineValueFontSize:(CGFloat)xLineValueFontSize{
    _xLineValueFontSize = xLineValueFontSize;
    self.genericChart.xLineValueFontSize = _xLineValueFontSize;
}

@end
